package ssh

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"hostname-and-ssh/model"
	"hostname-and-ssh/utils"
	"log"
	"time"
)

// NewSSHClient 创建一个 SSH 客户端
func NewSSHClient(host *model.Host) error {
	// 配置SSH
	config := &ssh.ClientConfig{
		User: host.User,
		Auth: []ssh.AuthMethod{
			ssh.Password(host.Password), // 密码认证
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 忽略主机密钥
		Timeout:         5 * time.Second,             // 连接超时时间
	}

	// 建立连接
	client, err := ssh.Dial("tcp", host.Address+":22", config)
	if err != nil {
		return fmt.Errorf("failed to dial: %w", err)
	}

	// 将建立的 SSH 客户端赋值给 Host 结构体
	host.Client = client

	log.Printf("SSH connection established to %s", host.Address)
	return nil
}

// CloseSSHClient 关闭 SSH 连接
func CloseSSHClient(host *model.Host) {
	if host.Client != nil {
		host.Client.Close()
		log.Printf("SSH connection to %s closed", host.Address)
	}
}

// ExecuteCommand 执行命令
func ExecuteCommand(host *model.Host, cmd string) (string, error) {
	if host.Client == nil {
		return "", fmt.Errorf("SSH client is nil")
	}
	// 创建一个新的SSH会话
	session, err := host.Client.NewSession()
	if err != nil {
		utils.LogError(fmt.Errorf("failed to create session: %w", err))
		return "", fmt.Errorf("failed to create session: %w", err)
	}
	defer session.Close()
	// 执行命令
	output, err := session.CombinedOutput(cmd)
	fmt.Println(string(output))
	if err != nil {
		utils.LogError(fmt.Errorf("failed to execute command: %w", err))
		return "", fmt.Errorf("failed to execute command: %w", err)
	}
	return string(output), nil
}
